/**
 * 文章提交 Composable
 * 
 * 处理文章创建和更新的提交逻辑
 */
import { useForm, router } from '@inertiajs/vue3'
import { useToast } from '@/Composables/useToast'

export function useArticleSubmit() {
  const toast = useToast()

  const buildForm = (initial) =>
    useForm({
      title: initial?.title ?? '',
      content: initial?.content ?? '',
      excerpt: initial?.excerpt ?? null,
      slug: initial?.slug ?? null,
      category_id: initial?.categoryId ?? null,
      tags: Array.isArray(initial?.tags) ? initial.tags.map((tag) => {
        // 如果标签是对象
        if (typeof tag === 'object' && tag !== null) {
          // 如果有 id，返回 id（已存在的标签）
          if (tag.id) {
            return tag.id;
          }
          // 如果没有 id 但有 name，返回 name（新创建的标签）
          if (tag.name) {
            return tag.name;
          }
          // 其他情况，返回原值
          return tag;
        }
        // 如果标签是字符串或数字，直接返回
        return tag;
      }) : [],
      series_id: initial?.seriesId ?? null,
      series_order: initial?.seriesOrder ?? null,
      sort_mode: initial?.sortMode ?? 'manual',
      status: initial?.status ?? 'draft',
      scheduled_publish_at: initial?.status === 'scheduled' ? initial?.scheduled_at ?? null : null,
      featured_image_url: initial?.featuredImageUrl ?? null,
    })

  const submitArticle = async (publishData, isEditMode, postSlug = null, clearDraft = null, editorStore = null) => {
    const form = buildForm(publishData)

    const url = isEditMode ? window.route('author.posts.update', postSlug) : window.route('author.posts.store')
    const method = isEditMode ? 'put' : 'post'

    return new Promise((resolve, reject) => {
      const options = {
        preserveState: true,
        onSuccess: (page) => {
          if (clearDraft && (publishData.status === 'published' || publishData.status === 'scheduled')) {
            clearDraft()
          }
          if (!isEditMode && editorStore && (publishData.status === 'published' || publishData.status === 'scheduled')) {
            editorStore.$reset()
          }
          if (publishData.status === 'published') toast.success('文章已成功发布')
          else if (publishData.status === 'scheduled') toast.success('文章已设置定时发布')
          else toast.success('草稿已保存')
          resolve(page)
        },
        onError: (errors) => {
          const list = Object.entries(errors || {}).map(([k, v]) => `${k}: ${Array.isArray(v) ? v.join(', ') : v}`).join('\n')
          toast.error(list || '提交失败')
          reject({ errors })
        },
      }

      if (method === 'put') form.put(url, options)
      else form.post(url, options)
    })
  }

  return {
    submitArticle,
  }
}

